import com.simple.redissonrpc.RedissonrpcApplication;
import com.simple.redissonrpc.core.RpcService;
import com.simple.redissonrpc.msg.TestAnswer;
import com.simple.redissonrpc.msg.TestAsk;
import com.simple.redissonrpc.msg.TestMessage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;

@Slf4j
@SpringBootTest(classes = RedissonrpcApplication.class)
public class TestRPC {

    @Autowired
    private RpcService rpcService;

    /**
     * 无返回值
     *
     * @throws Exception
     */
    @Test
    public void testSend() throws Exception {
        for (int i = 0; i < 10; i++) {
            TestMessage testMessage = new TestMessage();
            testMessage.setTag("这是一个send请求" + i);
            rpcService.send(1, testMessage);
        }

        TimeUnit.SECONDS.sleep(3);
    }

    /**
     * 同步等待返回
     *
     * @throws Exception
     */
    @Test
    public void testSyncCall() throws Exception {
        int num = 10000;
        long start = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            TestAsk testAsk = new TestAsk();
            testAsk.setTag("这是一个syncCall请求" + i);

            TestAnswer ret = rpcService.syncCall(1, testAsk, TestAnswer.class);
        }

        // 6s 1W次
        log.error("cost={}", System.currentTimeMillis() - start);
        TimeUnit.SECONDS.sleep(3);
    }

    /**
     * 异步有返回
     *
     * @throws Exception
     */
    @Test
    public void testAsyncCall() throws Exception {
        int num = 10000;
        AtomicInteger numObj = new AtomicInteger();
        long start = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            TestAsk testAsk = new TestAsk();
            testAsk.setTag("asyncCall消息" + i);
            rpcService.asyncCall(1, testAsk, TestAnswer.class, (ret) -> {
                if (numObj.incrementAndGet() >= num) {
                    // 3s 1W次
                    log.error("cost={}", System.currentTimeMillis() - start);
                }
            });
        }

        // 这个主要是避免单元测试直接退出. 实际生成环境肯定是不会退出的
        TimeUnit.SECONDS.sleep(5);
    }

}
